/*
 * Sesame Inc.
 * Copyright (c) 2009 All Rights Reserved.
 */
package com.sesame.controller.admin;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.sesame.domain.Album;
import com.sesame.domain.Image;
import com.sesame.domain.User;
import com.sesame.service.AdminService;
import com.sesame.service.AlbumService;
import com.sesame.service.SearchService;

/**
 * @author voidman
 * 
 */
public class AdminRebuildIndexController extends AbstractController {

    private AdminService adminService;
    private SearchService searchService;
    private AlbumService albumService;

    public void setAdminService(AdminService adminService) {
        this.adminService = adminService;
    }

    public void setSearchService(SearchService searchService) {
        this.searchService = searchService;
    }

    public void setAlbumService(AlbumService albumService) {
        this.albumService = albumService;
    }

    protected ModelAndView handleRequestInternal(HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        if ("admin".equals(request.getSession().getAttribute("adminRank"))) {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write("正在重建索引...");
            writer.flush();
            int totalUser = 0;
            int totalAlbum = 0;
            int totalImage = 0;
            try {

                List<User> userList = adminService.listAllUser();
                List<Album> albumList = albumService.listAllAlbum();
                List<Image> imageList = albumService.listAllImage();

                for (User user : userList)
                    searchService.reindex(user);

                for (Album album : albumList)
                    searchService.reindex(album);

                for (Image image : imageList)
                    searchService.reindex(image);

                write_dot(writer);
                totalUser = userList.size();
                totalAlbum = albumList.size();
                totalImage = imageList.size();

                writer.write("<br>完成！一共有" + totalUser + "个用户和" + totalAlbum
                        + "个相册和" + totalImage + "个图片被索引");
            } catch (Exception e) {
                writer.write("<br>错误：" + e.getMessage());
                writer.write("<br><pre>");
                e.printStackTrace(writer);
                writer.write("</pre>");
            }
            writer.flush();
            return null;
        } else {
            return new ModelAndView("redirect:adminError.html");
        }
    }

    private void write_dot(PrintWriter writer) throws IOException {
        writer.write(".");
        writer.flush();
    }

}